﻿<link href="/UI/css/components/components.min.css" rel="stylesheet" />
<link href="/Scripts/city-picker/css/city-picker.css" rel="stylesheet" />
<script src="/Scripts/city-picker/js/city-picker.min.js"></script>
<script src="https://webapi.amap.com/maps?v=1.4.15&key=9480cfd9f8b1527847a624c611c05ccd&plugin=AMap.Geocoder"></script>
<template>
    <div id="map-wrapper" :style="{'width':width,'height':height}">
        <input style="height:0" class="rgncoder"
               data-level="district"
               placeholder=" "/>
        <div class="FormItem map_searcher">
            <input id="tipinput" type="text" placeholder="请输入地址">
            <button class="input-after btn-ghost"><i class="soicon icon-fangdajing"></i></button>
        </div>
        <div :id="mapid" class="amap" ref="amap"></div>
    </div>
</template>
<script>
    vm_map = {
        props: {
            mapid: {
                type: String,
                default: 'amap'
            },
            width: {
                type: [String, Number],
                default: "100%"
            },
            height: {
                type: [String, Number],
                default: '400px'
            },
            lat: {
                type: String,
                default: ''
            },
            lng: {
                type: String,
                default: ''
            },
            addr: {
                type: String,
                default: ''
            },
            /**
             * 地图显示中心，根据传递地区查询地区中心经纬度，如果有传入经纬度属性，默认以传入的经纬度作为中心位置
             * （支持省市县市名称或编码查询）
             */
            mapcenter: {
                type: String,
                default: ''
            },
            district: {
                type: Object,
                default: {}
            },
            readonly: {
                type: Boolean,
                default: false
            }
        },
        watch: {
            /**
             * 地图中心位置值监听
             * （支持省市县市名称或编码查询）
             * @param value 省市县名称或编码
             */
            mapcenter: function (value) {
                var _this = this;
                var districtSearch = new AMap.DistrictSearch({
                    level: 'province'
                });
                districtSearch.search(value, function (status, result) {
                    if (status === 'complete' && result.districtList.length > 0) {
                        _this.mapObj.setCenter(result.districtList[0].center);
                    }
                });
            },
            /**
             * 县区值监听
             * （用于解决高德地图县区编码跟城市编码相同，无法定位地图中心点）
             * @param value parentAdcode上级地区编码，Adcode县区编码，Adname县区名称
             */
            district: function (value) {
                var _this = this;
                var districtSearch = new AMap.DistrictSearch({
                    level: 'province'
                });
                /*通过县区名称搜索，并根据城市地区编码过滤*/
                districtSearch.search(value.Adname, function (status, result) {
                    if (status === 'complete' && result.districtList.length > 0) {
                        var district = result.districtList.findObj('adcode', value.parentAdcode);
                        _this.mapObj.setCenter(district.center);
                    }
                });
            }
        },
        data: function () {
            return {
                mapObj: null,
                geoAddressObj: null,
                mapMarker: null,
                regionSlctor:null
            }
        },
        mounted: function () {
            //setTimeout(this.initMap, 100);
            this.initMap();
            this.regionSlctor = $('.rgncoder').eq(0);
            this.regionSlctor.citypicker({ readonly: true});
            //this.regionSlctor.on('cp:updated', this.onCityChanged);
        },
        methods: {
            initMap() {
                if (!window.AMap) {
                    setTimeout(this.initMap, 300);
                    return;
                }
                var _this = this;
                var map_initdata = {
                    resizeEnable: true,
                    zoom: 15
                }
                _this.mapObj = new AMap.Map(this.mapid, map_initdata);
                _this.initMapPlugn();

                /*根据经纬度设置地图标记*/
                if (this.lng !== '' && this.lat !== '') {
                    _this.mapObj.setCenter([this.lng, this.lat]);

                    _this.mapObj.clearMap();

                    _this.mapMarker = new AMap.Marker({
                        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                        position: new AMap.LngLat(this.lng, this.lat)
                    });
                    _this.mapObj.add(_this.mapMarker);
                    _this.setMarkerLabel(_this.addr);
                }

                /*绑定地图点击事件*/
                _this.mapObj.on('click', _this.setMarker);
            },
            /**初始化地图插件 */
            initMapPlugn: function () {
                var _this = this;
                _this.mapObj.plugin(['AMap.ToolBar', 'AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.DistrictSearch'], function () {
                    _this.mapObj.addControl(new AMap.ToolBar());

                    var autoOptions = {
                        input: "tipinput"//input的id
                    };
                    var autocomplete = new AMap.Autocomplete(autoOptions);
                    var placeSearch = new AMap.PlaceSearch({
                        map: _this.mapObj
                    })
                    AMap.event.addListener(autocomplete, "select", function (e) {
                        //TODO 针对选中的poi实现自己的功能
                        placeSearch.setCity(e.poi.adcode);
                        placeSearch.search(e.poi.name);
                    });
                });
            },
            setMarker: function (e) {
                if (this.readonly) return;
                var _this = this;
                /*清空地图标记*/
                this.mapObj.clearMap();
                /*构造地图点标记*/
                this.mapMarker = new AMap.Marker({
                    icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                    position: e.lnglat
                });
                this.mapObj.add(this.mapMarker);
                /*通过经纬度获取地址详细信息*/
                this.getAddress(e);

                //this.$emit('mapclick', e);
            },
            setMarkerLabel: function (title, content = '') {
                /*设置鼠标划过点标记显示的文字提示*/
                this.mapMarker.setTitle(title);

                /*设置label标签
                label默认蓝框白底左上角显示，样式className为：amap-marker-label*/
                this.mapMarker.setLabel({
                    offset: new AMap.Pixel(2.5, -2),  /*设置文本标注偏移量*/
                    content: content || title, /*设置文本标注内容*/
                    direction: 'right' /*设置文本标注方位*/
                });
            },
            getAddress: function (e) {
                var _this = this;
                var geocoder = new AMap.Geocoder({
                    radius: 1000
                });

                geocoder.getAddress(e.lnglat, function (status, result) {
                    if (status === 'complete') {
                        var addr = '根据经纬度查询地址失败';
                        if (result.regeocode) {
                            addr = result.regeocode.formattedAddress;
                        }
                        _this.setMarkerLabel(addr);
                        //_this.citycode = result.regeocode.addressComponent.adcode;
                        _this.regionSlctor.citypicker('reset');
                        _this.regionSlctor.citypicker('destroy');
                        _this.regionSlctor.citypicker({
                            province: result.regeocode.addressComponent.province,
                            city: result.regeocode.addressComponent.city,
                            district: result.regeocode.addressComponent.district ? result.regeocode.addressComponent.district : result.regeocode.addressComponent.township
                        });
                        var rgn = _this.regionSlctor.data('citypicker').getObj();
                        if (rgn) {
                            result.region = rgn;
                        }
                        else {
                            result.region = {
                                full_code: '',
                                full_name:''
                            };
                        }
                        _this.$emit('lnglat_changed', e, result);
                    }
                });
            },
            onCityChanged: function (e) {
                console.log('citychanged',e);
            }
        }
    }
</script>